import 'dart:convert';
import 'dart:core';
import 'dart:io';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:grpc/grpc.dart';
import 'package:member_center_sdk/grpc_impl/base_client_channel.dart';
import 'package:member_center_sdk/grpc_impl/grpc_client_call.dart';
import 'package:member_center_sdk/grpc_impl/grpc_context.dart';

class MemberClientChannel extends BaseClientChannel {
  String token;

  MemberClientChannel(host, port, this.token,
      {options = const ChannelOptions()})
      : super(host, port, options: options);



  @override
  ClientCall<Q, R> createCall<Q, R>(
      ClientMethod<Q, R> method, Stream<Q> requests, CallOptions options) {
    String requestId = "";
    if (options.metadata != null && options.metadata.containsKey("requestId")) {
      requestId = options.metadata["requestId"];
    } else {
      throw new Exception("非法请求");
    }
    var newOptions =
        options.mergedWith(CallOptions(metadata: {"token": token}));
    final call = new GrpcClientCall(requestId, method, requests, newOptions);
    getConnection().then((connection) {
      if (call.isCancelled) return;
      connection.dispatchCall(call);
    }, onError: call.onConnectionError);
    var cxt = GrpcContext();
    cxt.clientCall = call;
    cxtList[requestId] = cxt;

    return call;
  }

}
